package com.zhou.common.template.project.excel.handler;

/**
 * @author xianfeng
 * @date 2023/11/13 15:24
 * @description:
 */

import cn.afterturn.easypoi.handler.inter.IExcelDictHandler;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 模拟使用,生产请用真实字典
 *
 * @author jueyue on 20-4-26.
 */
@RequiredArgsConstructor
public class TestDictAddressListHandlerImpl implements IExcelDictHandler {

    public static final String RANK_DICT_CODE = "gov_res_rank";

    public static final String DEPT_DICT_CODE = "dept";

    /**
     * 职级的字典值 gov_res_rank
     */
    private final Map<String, String> govResRank;

    /**
     * 当前部门的所有子部门
     */
    private final Map<String, String> childOrgMap;

    public static <K, V> Map<V, K> reverse(Map<K, V> map) {
        return map.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
    }

    /**
     * 返回字典所有值
     * key: dictKey
     *
     * @param dict 字典Key
     * @return
     */
    @Override
    public List<Map> getList(String dict) {
        List<Map> list = new ArrayList<>();
        if (RANK_DICT_CODE.equals(dict)) {
            list.addAll(getMapList(govResRank));
        }
        if (DEPT_DICT_CODE.equals(dict)) {
            list.addAll(getMapList(childOrgMap));
        }
        return list;
    }

    @Override
    public String toName(String dict, Object obj, String name, Object value) {
        if (RANK_DICT_CODE.equals(dict) && value != null) {
            String rank = value.toString();
            return govResRank.get(rank);
        }
        if (DEPT_DICT_CODE.equals(dict) && value != null) {
            return childOrgMap.get(value.toString());
        }
        return null;
    }

    @Override
    public String toValue(String dict, Object obj, String name, Object value) {
        if (RANK_DICT_CODE.equals(dict) && value != null) {
            return reverse(govResRank).get(value.toString());
        }
        if (DEPT_DICT_CODE.equals(dict) && value != null) {
            return reverse(childOrgMap).get(value.toString());
        }
        return null;
    }

    private List<Map> getMapList(Map<String, String> map) {
        List<Map> collect = map.entrySet().stream().map(t -> {
            Map<String, String> dictMap = new HashMap<>();
            dictMap.put("dictKey", t.getKey());
            dictMap.put("dictValue", t.getValue());
            return dictMap;
        }).collect(Collectors.toList());
        return collect;
    }
}
